package 力扣._79_单词搜索;

class Solution {

    // now:当前待匹配的word下标
    boolean backtrack(char[][] board, String word, int now, int[][] visited, int i, int j) {
        if (now == word.length()) return true;
        int[][] direction = new int[][]{{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
        boolean isOK = false;
        for (int[] dir : direction) {
            i += dir[0];
            j += dir[1];
            if (i >= 0 && i < board.length && j >= 0 && j < board[0].length && board[i][j] == word.charAt(now) && visited[i][j] == 0) {
                visited[i][j] = 1;
                isOK = isOK || backtrack(board, word, now + 1, visited, i, j);
                visited[i][j] = 0;
            }
            i -= dir[0];
            j -= dir[1];
        }
        return isOK;


    }

    public boolean exist(char[][] board, String word) {
        boolean isOK = false;
        int m = board.length, n = board[0].length;
        int[][] visited = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == word.charAt(0)) {
                    visited[i][j] = 1;
                    if (backtrack(board, word, 1, visited, i, j))
                        return true;
                    visited[i][j] = 0;
                }

            }
        }
        return false;

    }

    public static void main(String[] args) {
        char[][] board = new char[][]{{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};
        String word = "ABCCED";
        boolean exist = new Solution().exist(board, word);
        System.out.println(exist);
    }
}